package service

import (
	"crypto/x509"
	"encoding/pem"
	"errors"
	"fmt"
	"github.com/go-admin-team/go-admin-core/sdk/service"
	"github.com/google/uuid"
	"gorm.io/gorm"
	"net/url"
	"strings"
	"time"
	"vrcm/src/vrcm/app/admin/models"
	"vrcm/src/vrcm/app/admin/models/domian"
	ccEngineService "vrcm/src/vrcm/app/admin/service/ccengine"
	ccenginDto "vrcm/src/vrcm/app/admin/service/dto/ccengine"
	"vrcm/src/vrcm/app/admin/service/dto/domian"
	"vrcm/src/vrcm/common/apis"
	cDto "vrcm/src/vrcm/common/dto"
)

type Certificate struct {
	service.Service
}

// GetPage 获取Certificate列表
func (e *Certificate) GetPage(c *dto.CertificateGetPageReq, count *int64) (*[]domain.CertificatePageModel, error) {
	var err error
	var data domain.Certificate
	res := make([]domain.CertificatePageModel, 0, 5)
	list := make([]domain.Certificate, 0, 5)
	err = e.Orm.Model(&data).
		Scopes(
			cDto.MakeCondition(c.GetNeedSearch()),
			cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
		).
		Find(&list).Limit(-1).Offset(-1).
		Count(count).Error
	if err != nil {
		e.Log.Errorf("CertificateService GetPage error:%s \r\n", err)
		return nil, err
	}

	ids := make([]int, 0, 5)
	for _, v := range list {
		v := v
		ids = append(ids, v.Id)
	}

	//allDomains := make([]domain.DomainConfig, 0, 5)
	//err = e.Orm.Model(&domain.DomainConfig{}).Where("tenant_id = ?", c.TenantId).Find(&allDomains).Error
	//if err != nil {
	//	e.Log.Errorf("get DomainConfig error:%s \r\n", err)
	//	return nil, err
	//}

	domains := make([]domain.DomainConfig, 0, 5)
	err = e.Orm.Model(&domain.DomainConfig{}).Where("certificate_id in ?", ids).Find(&domains).Error
	if err != nil {
		e.Log.Errorf("get DomainConfig error:%s \r\n", err)
		return nil, err
	}
	domainCertificateMap := make(map[int][]domain.DomainConfig)
	for _, v := range domains {
		v := v
		t, ok := domainCertificateMap[v.CertificateId]
		if !ok {
			t = make([]domain.DomainConfig, 0, 5)
		}
		t = append(t, v)
		domainCertificateMap[v.CertificateId] = t
	}

	//domainMap := make(map[string]domain.DomainConfig)
	//for _, v := range allDomains {
	//	v := v
	//	domainMap[v.AcDomain] = v
	//}
	now := time.Now().Unix()
	for _, v := range list {
		v := v
		model := domain.CertificatePageModel{}
		//model.AuthorizeDomains = make([]domain.DomainConfig, 0, 5)
		//判断证书状态
		if v.ValidTo < now {
			//已过期
			v.CertificateState = 3
		} else if (now + 30*24*60*60) > v.ValidTo {
			//还有一个月过期
			v.CertificateState = 2
		} else {
			v.CertificateState = 1
		}
		if c.CertificateState > 0 {
			if c.CertificateState == 3 {
				if v.CertificateState != c.CertificateState {
					continue
				}
			} else {
				if v.CertificateState == 3 {
					continue
				}
			}
		}
		model.Certificate = v
		d := domainCertificateMap[v.Id]
		model.CertificateDomains = d
		certificates := strings.Split(v.CertificateInfo, models.Delimiter)
		for _, certificate := range certificates {
			domain := domain.DomainConfig{}
			domain.AcDomain = certificate
			if certificate == c.AuthorizedDomain {
				if len(c.AuthorizedDomain) > 0 {
					model.AuthorizeDomains = append(model.AuthorizeDomains, domain)
					break
				}
			} else {
				model.AuthorizeDomains = append(model.AuthorizeDomains, domain)
			}
		}
		res = append(res, model)
	}
	//for k, domain := range domainMap {
	//	domain := domain
	//	arr := strings.Split(v.CertificateInfo, models.Delimiter)
	//	for _, s := range arr {
	//		cleanDomain := strings.TrimPrefix(s, "*.")
	//		if strings.Contains(k, cleanDomain) {
	//			model.AuthorizeDomains = append(model.AuthorizeDomains, domain)
	//			break
	//		}
	//	}
	//}

	//result := make([]domain.CertificatePageModel, 0, 5)
	//if len(c.AuthorizedDomain) > 0 {
	//	for _, re := range res {
	//		re := re
	//		flag := false
	//		for _, r := range re.AuthorizeDomains {
	//			if r.AcDomain == c.AuthorizedDomain {
	//				flag = true
	//				break
	//			}
	//		}
	//		if flag {
	//			result = append(result, re)
	//		}
	//
	//	}
	//	return &result, nil
	//}
	if c.CertificateState > 0 {
		*count = int64(len(res))
	}

	return &res, nil
}

// Get 获取Certificate对象
func (e *Certificate) Get(d *dto.CertificateGetReq) (*domain.CertificateModel, error) {
	var data domain.Certificate
	model := &domain.CertificateModel{}
	err := e.Orm.Model(&domain.Certificate{}).Where("id =?", d.Id).Find(&data).Error
	if err != nil {
		e.Log.Errorf("db error:%s", err)
		return nil, err
	}
	model.Certificate = data

	certificateDomains := make([]domain.CertificateDomain, 0, 5)
	err = e.Orm.Model(domain.CertificateDomain{}).Where("certificate_id = ?", d.Id).Find(&certificateDomains).Error
	if err != nil {
		e.Log.Errorf("get CertificateDomain  error:%s", err)
		return nil, err
	}

	model.CertificateDomains = certificateDomains

	return model, nil
}

func (e *Certificate) GetByCertId(d *dto.CertificateGetByCertIdReq) (*domain.CertificateModel, error) {
	var data domain.Certificate
	model := &domain.CertificateModel{}
	err := e.Orm.Model(&domain.Certificate{}).Where("cert_id =?", d.CertId).Find(&data).Error
	if err != nil {
		e.Log.Errorf("db error:%s", err)
		return nil, err
	}
	model.Certificate = data

	certificateDomains := make([]domain.CertificateDomain, 0, 5)
	err = e.Orm.Model(domain.CertificateDomain{}).Where("certificate_id = ?", data.Id).Find(&certificateDomains).Error
	if err != nil {
		e.Log.Errorf("get CertificateDomain  error:%s", err)
		return nil, err
	}

	model.CertificateDomains = certificateDomains

	return model, nil
}

func (e *Certificate) IsExitLiveBasic(tx *gorm.DB, c *dto.CertificateUpdateReq) bool {

	var basic domain.Certificate
	var err error

	b := domain.Certificate{}
	err = tx.Model(&domain.Certificate{}).Where("id=?", c.Id).Find(&b).Error
	if err != nil {
		return true
	}

	basicWhere := domain.Certificate{CertificateName: c.CertificateName, TenantId: c.TenantId}
	if c.Id > 0 {
		err = tx.Where(&basicWhere).Not("id =? or live_type = 2", c.Id).Find(&basic).Error
	} else {
		err = tx.Where(&basicWhere).Find(&basic).Error
	}

	if err != nil {
		return true
	}

	if basic.Id > 0 {
		return true
	}
	return false
}

// Insert 创建Certificate对象
func (e *Certificate) Insert(c *dto.CertificateInsertReq) error {
	tx := e.Orm.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()
	if err := tx.Error; err != nil {
		return err
	}

	b := e.IsExitLiveBasic(tx, &dto.CertificateUpdateReq{TenantId: c.TenantId, CertificateName: c.CertificateName, Id: c.Id})
	if b {
		return errors.New(string(apis.CertificateNameError.Code))
	}

	res, err := e.CheckPem(&ccenginDto.CheckPemReq{Pem: c.PublicKey})
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("CheckPem error:%s \r\n", err)
		return errors.New("证书校验失败")
	}

	name, err := e.GetAuthorizedDomain([]byte(c.PublicKey))
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("GetAuthorizedDomain error:%s \r\n", err)
		return err
	}

	layout := "2006-01-02T15:04:05.000Z"
	var data domain.Certificate
	c.Generate(&data)
	data.CertificateInfo = name
	from, err := time.ParseInLocation(layout, res.ValidFrom, time.Local)
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("parse time error:", err)
		return err
	}
	data.ValidFrom = from.Unix()
	to, err := time.ParseInLocation(layout, res.ValidTo, time.Local)
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("parse time error:", err)
		return err
	}
	data.ValidFrom = from.Unix()
	data.ValidTo = to.Unix()
	err = tx.Create(&data).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("CertificateService Insert error:%s \r\n", err)
		return err
	}
	c.CertId = data.CertId

	ccEngineService := ccEngineService.CCEngineService{}
	ccEngineService.Log = e.Log
	certificates := make([]domain.Certificate, 0, 5)
	err = tx.Model(&domain.Certificate{}).Where("tenant_id=?", c.TenantId).Find(&certificates).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("get Certificate error:%s \r\n", err)
		return err
	}
	ssls := make([]ccenginDto.SslCertification, 0, 5)
	for _, v := range certificates {
		ssl := ccenginDto.SslCertification{}
		ssl.Name = v.CertificateId
		ssl.SslKey = v.PublicKey
		ssl.SslCert = v.PrivateKey
		ssls = append(ssls, ssl)
	}
	err = ccEngineService.SetCertificate(&ccenginDto.CertificateReq{TenantId: c.TenantId, SslCertification: ssls})
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("set Certificate error:%s \r\n", err)
		return err
	}
	tx.Commit()
	return nil
}

func (e *Certificate) GetAuthorizedDomain(certData []byte) (string, error) {
	block, _ := pem.Decode(certData)
	if block == nil {
		return "", nil
	}
	cert, err := x509.ParseCertificate(block.Bytes)
	if err != nil {
		e.Log.Errorf("ParseCertificate error:%s \r\n", err)
		return "", err
	}
	name := strings.Join(cert.DNSNames, models.Delimiter)
	return name, nil

}

// Update 修改Certificate对象
func (e *Certificate) Update(c *dto.CertificateUpdateReq) error {
	tx := e.Orm.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()
	if err := tx.Error; err != nil {
		return err
	}
	domainConfig := &domain.DomainConfig{}
	err := tx.Model(&domain.DomainConfig{}).Where("id=?", c.DomainId).Find(&domainConfig).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("get DomainConfig error:%s \r\n", err)
		return err
	}
	if domainConfig.Id <= 0 {
		tx.Rollback()
		return errors.New(string(apis.DomainExistError.Code))
	}

	//b := e.IsExitLiveBasic(tx, &dto.CertificateUpdateReq{TenantId: c.TenantId, CertificateName: c.CertificateName, Id: c.Id})
	//if b {
	//	tx.Rollback()
	//	return errors.New(string(apis.CertificateNameError.Code))
	//}
	//校验证书
	res, err := e.CheckPem(&ccenginDto.CheckPemReq{Pem: c.PublicKey})
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("CheckPem error:%s \r\n", err)
		return errors.New("证书校验失败")
	}

	name, err := e.GetAuthorizedDomain([]byte(c.PublicKey))
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("GetAuthorizedDomain error:%s \r\n", err)
		return err
	}

	layout := "2006-01-02T15:04:05.000Z"
	var data = domain.Certificate{}
	tx.First(&data, c.GetId())
	if data.Id <= 0 {
		tx.Rollback()
		return errors.New(string(apis.CertificateExistError.Code))
	}
	c.Generate(&data)

	data.CertificateInfo = name
	from, err := time.ParseInLocation(layout, res.ValidFrom, time.Local)
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("parse time error:", err)
		return err
	}
	data.ValidFrom = from.Unix()
	to, err := time.ParseInLocation(layout, res.ValidTo, time.Local)
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("parse time error:", err)
		return err
	}
	data.ValidFrom = from.Unix()
	data.ValidTo = to.Unix()

	db := tx.Save(&data)
	if err = db.Error; err != nil {
		tx.Rollback()
		e.Log.Errorf("CertificateService Save error:%s \r\n", err)
		return err
	}
	param := make(map[string]interface{})
	param["certificate_id"] = data.Id
	param["update_time"] = time.Now().Unix()
	err = tx.Model(&domain.DomainConfig{}).Where("id=?", c.DomainId).Updates(&param).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("update DomainConfig error:%s \r\n", err)
		return err
	}
	c.Id = data.Id
	tx.Commit()
	return nil
}

// Remove 删除Certificate
func (e *Certificate) Remove(d *dto.CertificateDeleteReq) error {
	tx := e.Orm.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()
	if err := tx.Error; err != nil {
		return err
	}

	//获取配置证书的域名
	domains := make([]int, 0, 5)
	err := tx.Model(&domain.DomainConfig{}).Select("id").Where("certificate_id in ?", d.Ids).Find(&domains).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("get DomainConfig error:%s \r\n", err)
		return err
	}

	if len(domains) > 0 {
		tx.Rollback()
		e.Log.Errorf("已绑定域名")
		return errors.New("已绑定域名")
	}

	var data domain.Certificate
	db := tx.Model(&data).Where("id in ?", d.Ids).Delete(&data)
	if err := db.Error; err != nil {
		tx.Rollback()
		e.Log.Errorf("Service RemoveCertificate error:%s \r\n", err)
		return err
	}

	////获取配置证书的域名
	//domains := make([]int, 0, 5)
	//err := tx.Model(&domain.DomainConfig{}).Select("id").Where("certificate_id in ?", d.Ids).Find(&domains).Error
	//if err != nil {
	//	tx.Rollback()
	//	e.Log.Errorf("get DomainConfig error:%s \r\n", err)
	//	return err
	//}

	//更新证书域名关系
	if len(domains) > 0 {
		param := make(map[string]interface{})
		param["certificate_id"] = 0
		param["update_time"] = time.Now().Unix()
		err := tx.Model(&domain.DomainConfig{}).Where("id in ?", domains).Updates(&param).Error
		if err != nil {
			tx.Rollback()
			e.Log.Errorf("update DomainConfig error:%s \r\n", err)
			return err
		}
	}
	tx.Commit()
	return nil
}

func (e *Certificate) RemoveByCertId(d *dto.CertificateRemoveReq) error {
	tx := e.Orm.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()
	if err := tx.Error; err != nil {
		return err
	}

	var data domain.Certificate
	db := tx.Model(&data).Where("cert_id = ?", d.CertId).Delete(&data)
	if err := db.Error; err != nil {
		tx.Rollback()
		e.Log.Errorf("Service RemoveCertificate error:%s \r\n", err)
		return err
	}

	//获取配置证书的域名
	domains := make([]int, 0, 5)
	err := tx.Model(&domain.DomainConfig{}).Select("id").Where("certificate_id = ?", data.Id).Find(&domains).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("get DomainConfig error:%s \r\n", err)
		return err
	}

	//更新证书域名关系
	if len(domains) > 0 {
		param := make(map[string]interface{})
		param["certificate_id"] = 0
		param["update_time"] = time.Now().Unix()
		err := tx.Model(&domain.DomainConfig{}).Where("id in ?", domains).Updates(&param).Error
		if err != nil {
			tx.Rollback()
			e.Log.Errorf("update DomainConfig error:%s \r\n", err)
			return err
		}
	}
	tx.Commit()
	return nil
}

func (e *Certificate) Refresh(d *dto.RefreshSaveReq) (string, error) {
	tx := e.Orm.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()
	if err := tx.Error; err != nil {
		return "", err
	}

	var config domain.DomainConfig
	err := tx.Model(&domain.DomainConfig{}).Where("id=?", d.DomainId).Find(&config).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("get DomainConfig  error:%s \r\n", err)
		return "", err
	}
	now := time.Now().Unix()
	data := make([]domain.RefreshConfig, 0, 5)
	paths := ccenginDto.Paths{}
	urls := make([]string, 0, 5)
	dirs := make([]string, 0, 5)
	taskId := uuid.New().String()
	domainUrlMap := make(map[string][]string)
	refreshConfigMap := make(map[string][]domain.RefreshConfig)
	if len(d.Urls) > 0 {
		for _, v := range d.Urls {
			v := v
			r := domain.RefreshConfig{}
			r.TenantId = d.TenantId
			r.OperateType = d.OperateType
			r.OperateModel = d.OperateModel
			r.Url = v
			r.DomainId = d.DomainId
			r.CreateTime = now
			r.UpdateTime = now
			r.RefreshState = 1
			r.TaskId = taskId
			data = append(data, r)

			u, err := url.Parse(v)
			if err != nil {
				fmt.Println("解析 URL 失败：", err)
				return "", errors.New("解析 URL 失败")
			}
			host := u.Hostname()
			url, ok := domainUrlMap[host]
			if !ok {
				url = make([]string, 0, 5)
			}
			url = append(url, v)
			domainUrlMap[host] = url
		}
		err = tx.Model(&domain.RefreshConfig{}).Create(&data).Error
		if err != nil {
			tx.Rollback()
			e.Log.Errorf("insert RefreshConfig  error:%s \r\n", err)
			return "", err
		}
		for _, refreshConfig := range data {
			refreshConfig := refreshConfig
			refreshConfigs, ok := refreshConfigMap[refreshConfig.Url]
			if !ok {
				refreshConfigs = make([]domain.RefreshConfig, 0, 3)
			}
			refreshConfigs = append(refreshConfigs, refreshConfig)
			refreshConfigMap[refreshConfig.Url] = refreshConfigs
		}
	}
	names := make([]string, 0, 5)
	//获取域名
	for k, _ := range domainUrlMap {
		k := k
		names = append(names, k)
	}

	//获取加速域名
	domains := make([]domain.DomainConfig, 0, 5)
	err = tx.Model(&domain.DomainConfig{}).Where("ac_domain in ?", names).Find(&domains).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("get DomainConfig  error:%s \r\n", err)
		return "", err
	}

	//存储加速域名和任务id关系
	domainTaskMap := make(map[string]string)
	for _, v := range domains {
		v := v
		domainTaskMap[v.AcDomain] = v.DomainTaskId
	}
	ccEngineService := ccEngineService.CCEngineService{}
	ccEngineService.Log = e.Log
	for k, url := range domainUrlMap {
		//根据域名获取任务id
		taskId := domainTaskMap[k]

		//存到url或者目录
		if d.OperateModel == 1 {
			urls = append(urls, url...)
		} else {
			dirs = append(dirs, url...)
		}
		paths.Uri = urls
		paths.Dir = dirs
		//预热
		reFreshTaskId := ""
		if d.OperateType == 2 {
			reFreshTaskId, err = ccEngineService.PreHotUrl(&ccenginDto.PreHotUrlReq{Id: taskId, TenantId: d.TenantId, Paths: paths})
			if err != nil {
				tx.Rollback()
				e.Log.Errorf("PreHotUrl  error:%s \r\n", err)
				return "", err
			}
		} else {
			//刷新
			reFreshTaskId, err = ccEngineService.RefreshCache(&ccenginDto.PreHotUrlReq{Id: taskId, TenantId: d.TenantId, Paths: paths})
			if err != nil {
				tx.Rollback()
				e.Log.Errorf("RefreshCache  error:%s \r\n", err)
				return "", err
			}
		}
		for _, path := range url {
			refreshConfigs := refreshConfigMap[path]
			for k, _ := range refreshConfigs {
				*(&refreshConfigs[k].RefreshTaskId) = reFreshTaskId
			}
			err = tx.Save(refreshConfigs).Error
			if err != nil {
				tx.Rollback()
				e.Log.Errorf("save refreshConfig  error:%s \r\n", err)
				return "", err
			}
		}

	}

	tx.Commit()

	return taskId, nil
}

func (e *Certificate) RefreshWithTaskId(d *dto.RefreshSaveReq) (string, error) {
	tx := e.Orm.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()
	if err := tx.Error; err != nil {
		return "", err
	}

	var config domain.DomainConfig
	err := tx.Model(&domain.DomainConfig{}).Where("id=?", d.DomainId).Find(&config).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("get DomainConfig  error:%s \r\n", err)
		return "", err
	}
	now := time.Now().Unix()
	data := make([]domain.RefreshConfig, 0, 5)
	paths := ccenginDto.Paths{}
	urls := make([]string, 0, 5)
	dirs := make([]string, 0, 5)
	taskId := uuid.New().String()
	domainUrlMap := make(map[string][]string)
	refreshConfigMap := make(map[string][]domain.RefreshConfig)
	if len(d.Urls) > 0 {
		for _, v := range d.Urls {
			v := v
			r := domain.RefreshConfig{}
			r.TenantId = d.TenantId
			r.OperateType = d.OperateType
			r.OperateModel = d.OperateModel
			r.Url = v
			r.DomainId = d.DomainId
			r.CreateTime = now
			r.UpdateTime = now
			r.TaskId = taskId
			data = append(data, r)

			u, err := url.Parse(v)
			if err != nil {
				fmt.Println("解析 URL 失败：", err)
				return "", errors.New("解析 URL 失败")
			}
			host := u.Hostname()
			url, ok := domainUrlMap[host]
			if !ok {
				url = make([]string, 0, 5)
			}
			url = append(url, v)
			domainUrlMap[host] = url
		}
		err = tx.Model(&domain.RefreshConfig{}).Create(&data).Error
		if err != nil {
			tx.Rollback()
			e.Log.Errorf("insert RefreshConfig  error:%s \r\n", err)
			return "", err
		}
		for _, refreshConfig := range data {
			refreshConfig := refreshConfig
			refreshConfigs, ok := refreshConfigMap[refreshConfig.Url]
			if !ok {
				refreshConfigs = make([]domain.RefreshConfig, 0, 3)
			}
			refreshConfigs = append(refreshConfigs, refreshConfig)
			refreshConfigMap[refreshConfig.Url] = refreshConfigs
		}
	}
	names := make([]string, 0, 5)
	//获取域名
	for k, _ := range domainUrlMap {
		k := k
		names = append(names, k)
	}

	//获取加速域名
	domains := make([]domain.DomainConfig, 0, 5)
	err = tx.Model(&domain.DomainConfig{}).Where("ac_domain in ?", names).Find(&domains).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("get DomainConfig  error:%s \r\n", err)
		return "", err
	}

	//存储加速域名和任务id关系
	domainTaskMap := make(map[string]string)
	for _, v := range domains {
		v := v
		domainTaskMap[v.AcDomain] = v.DomainTaskId
	}
	ccEngineService := ccEngineService.CCEngineService{}
	ccEngineService.Log = e.Log
	for k, url := range domainUrlMap {
		//根据域名获取任务id
		taskId := domainTaskMap[k]

		//存到url或者目录
		if d.OperateModel == 1 {
			urls = append(urls, url...)
		} else {
			dirs = append(dirs, url...)
		}
		paths.Uri = urls
		paths.Dir = dirs
		reFreshTaskId := ""
		//预热
		if d.OperateType == 2 {
			reFreshTaskId, err = ccEngineService.PreHotUrl(&ccenginDto.PreHotUrlReq{Id: taskId, TenantId: d.TenantId, Paths: paths})
			if err != nil {
				tx.Rollback()
				e.Log.Errorf("PreHotUrl  error:%s \r\n", err)
				return "", err
			}
		} else {
			//刷新
			reFreshTaskId, err = ccEngineService.RefreshCache(&ccenginDto.PreHotUrlReq{Id: taskId, TenantId: d.TenantId, Paths: paths})
			if err != nil {
				tx.Rollback()
				e.Log.Errorf("RefreshCache  error:%s \r\n", err)
				return "", err
			}
		}
		for _, path := range url {
			refreshConfigs := refreshConfigMap[path]
			for k, _ := range refreshConfigs {
				*(&refreshConfigs[k].RefreshTaskId) = reFreshTaskId
			}
			err = tx.Save(refreshConfigs).Error
			if err != nil {
				tx.Rollback()
				e.Log.Errorf("save refreshConfig  error:%s \r\n", err)
				return "", err
			}
		}
	}

	tx.Commit()

	return taskId, nil
}

func (e *Certificate) GetRefreshRecord(d *dto.RefreshGetReq) (*[]domain.RefreshConfig, error) {

	data := make([]domain.RefreshConfig, 0, 5)
	db := e.Orm.Model(domain.RefreshConfig{}).Where("tenant_id=? ", d.TenantId)
	if d.OperateType > 0 {
		db.Where("operate_type=?", d.OperateType)
	}
	if d.StartTime > 0 {
		db.Where("create_time>= ? and create_time<=?", d.StartTime, d.EndTime)
	}
	if len(d.TaskId) > 0 {
		db.Where("task_id= ?", d.TaskId)
	}
	err := db.Find(&data).Error
	if err != nil {
		e.Log.Errorf("get RefreshConfig error:%s \r\n", err)
		return nil, err
	}

	return &data, nil
}

func (e *Certificate) GetRefreshRecordPage(d *dto.RefreshRecordGetPageReq, count *int64) (*[]domain.RefreshConfig, error) {

	var err error
	var data domain.RefreshConfig
	list := make([]domain.RefreshConfig, 0, 5)
	db := e.Orm.Model(&data).
		Scopes(
			cDto.MakeCondition(d.GetNeedSearch()),
			cDto.Paginate(d.GetPageSize(), d.GetPageIndex()),
		)
	if d.StartTime > 0 {
		db.Where("create_time>= ? and create_time<=?", d.StartTime, d.EndTime)
	}
	if len(d.TaskId) > 0 {
		db.Where("task_id= ?", d.TaskId)
	}

	if d.RefreshState > 0 {
		db.Where("refresh_state= ?", d.RefreshState)
	}
	err = db.Find(&list).Limit(-1).Offset(-1).
		Count(count).Error
	if err != nil {
		e.Log.Errorf("GetRefreshRecordPage GetPage error:%s \r\n", err)
		return nil, err
	}

	return &list, nil
}

func (e *Certificate) CancelCertificateDomain(d *dto.CancelCertificateDomainReq) error {

	param := make(map[string]interface{})
	param["certificate_id"] = 0
	param["update_time"] = time.Now().Unix()
	err := e.Orm.Model(&domain.DomainConfig{}).Where("id=? and certificate_id=?", d.DomainId, d.CertificateId).Updates(&param).Error
	if err != nil {
		e.Log.Errorf("update DomainConfig error:%s \r\n", err)
		return err
	}
	return nil
}

func (e *Certificate) CheckPem(d *ccenginDto.CheckPemReq) (*ccenginDto.CheckPemRes, error) {
	ccEngineService := ccEngineService.CCEngineService{}
	ccEngineService.Log = e.Log
	res, err := ccEngineService.CheckPem(d)
	if err != nil {
		e.Log.Errorf("CheckPem error:%s \r\n", err)
		return nil, err
	}
	return res, nil
}
